#!/usr/bin/python3

import sys
import re

from myutils import is_internal_ip
from QQWry import QQWry
import ipdb

# v6 version comes from https://stackoverflow.com/a/17871737/296473
ip_re = re.compile(r'''
((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?) # IPv4
# |::ffff:(0:)?((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?) # IPv4 mapped / translated addresses
# |fe80:(:[0-9a-fA-F]{1,4}){0,4}(%\w+)? # IPv6 link-local
|([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4} # IPv6 full
|(([0-9a-fA-F]{1,4}:){0,6}[0-9a-fA-F]{1,4})?::(([0-9a-fA-F]{1,4}:){0,6}[0-9a-fA-F]{1,4})? # IPv6 with ::
''', re.VERBOSE)

Q = QQWry()
D = ipdb.IPDB(ipdb.DEFAULT_FILE_LOCATION)

def lookupip(ip):
  if '.' in ip:
    return ''.join(Q[ip][2:])
  else:
    return ' '.join(D.lookup(ip).info).replace('\t', ' ')

def transformline(l):
  shift = 0
  for m in ip_re.finditer(l):
    try:
      ip = m.group(0)
      if ip.count(':') > 7:
        rest = ip.split(':', 8)[-1]
        end = len(ip) - len(rest)
        ip = ip[:end]
      else:
        end = m.end()

      if is_internal_ip(ip):
        continue

      addr = lookupip(ip)
      inspos = end + shift
      l = '%s(%s)%s' % (l[:inspos], addr, l[inspos:])
      shift += len(addr) + 2
    except Exception:
      pass
  return l

def main():
  for l in sys.stdin:
    sys.stdout.write(transformline(l))

if __name__ == '__main__':
  try:
    main()
  except (KeyboardInterrupt, IOError):
    pass
